<?php
/**
 * 供货商管理
 */
Class SupplierControl extends SystemControl{

    public function __construct()
    {
        parent::__construct();
    }
    /**
     *  首页
     */
     public function IndexOp(){
          $this->SupplierListOp();
     }

     /**
      * 供货商列表
      */
    public function SupplierListOp(){
        Tpl::setDirquna('shop');
        Tpl::showpage('Supplier.list');
    }

    /**
     * 返回xml 格式
     */
    public function getSupplierXmlOp(){
        $model_store = Model('store');
        // 设置页码参数名称
        $condition = array();
        $condition['is_own_shop'] = 0;
        $condition['store_class'] = 3;
        if ($_GET['store_name'] != '') {
            $condition['store_name'] = array('like', '%' . $_GET['store_name'] . '%');
        }
        if ($_GET['member_name'] != '') {
            $condition['member_name'] = array('like', '%' . $_GET['member_name'] . '%');
        }
        if ($_GET['seller_name'] != '') {
            $condition['seller_name'] = array('like', '%' . $_GET['seller_name'] . '%');
        }

        if ($_GET['grade_id'] != '') {
            $condition['grade_id'] = $_GET['grade_id'];
        }
        if ($_GET['store_state'] != '') {
            $condition['store_state'] = $_GET['store_state'];
        }
        if ($_POST['query'] != '') {
            $condition[$_POST['qtype']] = array('like', '%' . $_POST['query'] . '%');
            $condition['store_class'] = $_POST['class'];
        }

        $order = '';
        $param = array('store_id', 'store_name', 'store_class', 'member_name', 'seller_name', 'store_time', 'store_end_time', 'store_state', 'grade_id', 'sc_id');
        if (in_array($_POST['sortname'], $param) && in_array($_POST['sortorder'], array('asc', 'desc'))) {
            $order = $_POST['sortname'] . ' ' . $_POST['sortorder'];
        }

        $page = $_POST['rp'];

        //店铺列表
        $store_list = $model_store->getStoreList($condition, $page, $order);

        //店铺等级
        $model_grade = Model('store_grade');
        $grade_list = $model_grade->getGradeList(array());
        $grade_array = array();
        if (!empty($grade_list)) {
            foreach ($grade_list as $v) {
                $grade_array[$v['sg_id']] = $v['sg_name'];
            }
        }

        //店铺分类
        $model_store_class = Model('store_class');
        $class_list = $model_store_class->getStoreClassList(array(), '', false);
        $class_array = array();
        if (!empty($class_list)) {
            foreach ($class_list as $v) {
                $class_array[$v['sc_id']] = $v['sc_name'];
            }
        }

        $data = array();
        $data['now_page'] = $model_store->shownowpage();
        $data['total_num'] = $model_store->gettotalnum();
        foreach ($store_list as $value) {
            $param = array();
            $store_state = $this->getStoreState($value);
            $operation = "<span class='btn'><em><i class='fa fa-cog'></i>" . L('nc_set') . " <i class='arrow'></i></em><ul><li><a href='index.php?act=supplier&op=Supplier_edit&store_id=" . $value['store_id'] . "'>编辑供应商信息</a></li></li>";
            if (str_cut($store_state, 6) == 'expire' && cookie('remindRenewal' . $value['store_id']) == null) {
                $operation .= "<li><a class='expire' href=" . urlAdminShop('store', 'remind_renewal', array('store_id' => $value['store_id'])) . ">提醒商家续费</a></li>";
            }
            $operation .= "</ul></span>";
            $param['operation'] = $operation;
            $param['store_id'] = $value['store_id'];
            $store_name = "<a class='" . $store_state . "' href='" . urlShop('show_store', 'index', array('store_id' => $value['store_id'])) . "' target='blank'>";
            if ($store_state == 'expired') {
                $store_name .= "<i class='fa fa-clock-o' title='该店铺已过期，可从编辑菜单提醒续费'></i>";
            } else if ($store_state == 'expire') {
                $store_name .= "<i class='fa fa-bell-o' title='该店铺即将到期，可从编辑菜单提醒续费'></i>";
            }
            $store_name .= $value['store_name'] . "<i class='fa fa-external-link ' title='新窗口打开'></i></a>";
            $param['store_name'] = $store_name;
            $param['seller_name'] = $value['seller_name'];
            $param['store_time'] = date('Y-m-d', $value['store_time']);
            $data['list'][$value['store_id']] = $param;
        }
        echo Tpl::flexigridXML($data);
        exit();
    }

    /**
     * 获得店铺状态
     *  open\正常
     *  close\关闭
     *  expire\即将到期
     *  expired\过期
     */
    private function getStoreState($store_info)
    {
        $result = 'open';
        if (intval($store_info['store_state']) === 1) {
            $store_end_time = intval($store_info['store_end_time']);
            if ($store_end_time > 0) {
                if ($store_end_time < TIMESTAMP) {
                    $result = 'expired';
                } elseif (($store_end_time - 864000) < TIMESTAMP) {
                    //距离到期10天
                    $result = 'expire';
                }
            }
        } else {
            $result = 'close';
        }
        return $result;
    }

    public function SupplierAddOp(){
        if (chksubmit()) {
            $storeName = $_POST['store_name'];
            $memberletters = $_POST['store_letters'];
            $memberPass = $_POST['seller_password'];
            if (strlen($_POST['supplier_name']) > 3 && strlen($_POST['supplier_name']) < 15)
                showMessage('名称必须是3~15位', '', 'html', 'error');
            if (strlen($memberPass) < 6)
                showMessage('登录密码不能短于6位', '', 'html', 'error');
            if (!$this->checkMemberName($_POST['supplier_name']))
                showMessage('供货商账号已被占用', '', 'html', 'error');

            if (!$this->checkSellerName($_POST['supplier_name']))
                showMessage('供货商账号名称已被其它店铺占用', '', 'html', 'error');

            if (!$this->CheckChars($memberletters)) {
                showMessage('供货商首字母填写错误', '', 'html', 'error');
            }
            try {
                $memberId = model('member')->addMember(array(
                    'member_name' => $_POST['Supplier_name'],
                    'member_passwd' => $memberPass,
                    'type' => '3', // 供应商
                    'member_email' => '',
                ));
            } catch (Exception $ex) {
                showMessage('供货商账号新增失败', '', 'html', 'error');
            }
            $saveArray = array();
            $storeModel = model('store');

            $saveArray['store_name'] = $storeName;
            $saveArray['store_class'] = 3;  // 供货商
            $saveArray['store_letters'] = strtoupper($_POST['store_letters']);
            $saveArray['area_info'] = $_POST['region'];
            $saveArray['province_id'] = $_POST['province_id'];
            $saveArray['city_id'] = $_POST['city_id'];
            $saveArray['area_id'] = $_POST['area_id'];
            $saveArray['member_id'] = $memberId;
            $saveArray['member_name'] = $_POST['Supplier_name'];
            $saveArray['seller_name'] = $_POST['Supplier_name'];
            $saveArray['bind_all_gc'] = 1;
            $saveArray['store_state'] = 1;
            $saveArray['store_time'] = time();
            $saveArray['is_own_shop'] = 0;
            $storeId = $storeModel->addStore($saveArray);

            model('seller')->addSeller(array(
                'seller_name' => $_POST['Supplier_name'],
                'member_id' => $memberId,
                'store_id' => $storeId,
                'seller_group_id' => 0,
                'is_admin' => 1,
            ));
            model('store_joinin')->save(array(
                'seller_name' => $_POST['Supplier_name'],
                'store_name' => $_POST['store_name'],
                'member_name' => $_POST['Supplier_name'],
                'member_id' => $memberId,
                'joinin_state' => 40,
                'company_province_id' => 0,
                'sc_bail' => 0,
                'joinin_year' => 1,
            ));

            // 添加相册默认
            $album_model = Model('album');
            $album_arr = array();
            $album_arr['aclass_name'] = '默认相册';
            $album_arr['store_id'] = $storeId;
            $album_arr['aclass_des'] = '';
            $album_arr['aclass_sort'] = '255';
            $album_arr['aclass_cover'] = '';
            $album_arr['upload_time'] = time();
            $album_arr['is_default'] = '1';
            $album_model->addClass($album_arr);

            //插入店铺扩展表
            $model = Model();
            $model->table('store_extend')->insert(array('store_id' => $storeId));

            // 删除自营店id缓存
            Model('store')->dropCachedOwnShopIds();

            $this->log("新增外驻供应商: {$saveArray['store_name']}");
            showMessage('操作成功', 'index.php?act=supplier');
            return;
        }
        Tpl::setDirquna('shop');
        Tpl::showpage('supplier.add');
    }


    /**
     * 供应商编辑
     */
    public function Supplier_editOp(){
        $lang = Language::getLangContent();
        $model_store = Model('store');
        //保存
        if (chksubmit()) {
            if (!$this->CheckChars($_POST['store_letters'])) {
                showMessage('供货商首字母填写错误', '', 'html', 'error');
            }
            $update_array = array();
            $update_array['store_name'] = trim($_POST['store_name']);
            $update_array['store_letters'] = strtoupper(trim($_POST['store_letters']));
            $result = $model_store->editStore($update_array, array('store_id' => $_POST['store_id']));
            if ($result) {
                $url = array(
                    array(
                        'url' => 'index.php?act=supplier',
                        'msg' => $lang['back_store_list'],
                    ),
                    array(
                        'url' => 'index.php?act=supplier&op=Supplier_edit&store_id=' . intval($_POST['store_id']),
                        'msg' => $lang['countinue_add_store'],
                    ),
                );
                $this->log(L('nc_edit,store') . '[' . $_POST['store_name'] . ']', 1);
                showMessage($lang['nc_common_save_succ'], $url);
            } else {
                $this->log(L('nc_edit,store') . '[' . $_POST['store_name'] . ']', 1);
                showMessage($lang['nc_common_save_fail']);
            }
        }
        //取店铺信息
        $store_array = $model_store->getStoreInfoByID($_GET['store_id']);
        if (empty($store_array)) {
            showMessage("供应商不存在");
        }
        Tpl::output('store_array', $store_array);
        Tpl::setDirquna('shop');
        Tpl::showpage('supplier.edit');
    }

    private function checkSellerName($sellerName, $storeId = 0)
    {
        // 判断store_joinin是否存在记录
        $count = (int)Model('store_joinin')->getStoreJoininCount(array(
             'seller_name' => $sellerName,
        ));
        if ($count > 0)
            return false;

        $seller = Model('seller')->getSellerInfo(array(
            'seller_name' => $sellerName,
        ));

        if (empty($seller))
            return true;

        if (!$storeId)
            return false;

        if ($storeId == $seller['store_id'] && $seller['seller_group_id'] == 0 && $seller['is_admin'] == 1)
            return true;

        return false;
    }

    //检测是否为字母
    private function CheckChars($str)
    {
        if (empty($str)) return false;
        return (bool)preg_match("/^([a-z\s]*)$/isU", $str);
    }

    private function checkMemberName($memberName)
    {
        // 判断store_joinin是否存在记录
        $count = (int)Model('store_joinin')->getStoreJoininCount(array(
            'member_name' => $memberName,
        ));
        if ($count > 0)
            return false;

        return !Model('member')->getMemberCount(array(
            'member_name' => $memberName,
        ));
    }

}